# coding=utf-8
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response

from django.core import serializers
from django.utils import simplejson
from django.template import Template
from django.template import Context

import template

from google.appengine.api import users
from google.appengine.ext import db

from blog.models import Category
from blog.models import Diary
from blog.models import Tag
from blog.models import Comment
from link.models import Link

def gen_general_page(request, extra_context):
	login_user = users.get_current_user()
	login_url = users.create_login_url(request.get_full_path())
	is_user_admin = users.is_current_user_admin()
	logout_url = users.create_logout_url(request.get_full_path())

	context = {'login_url':login_url,
			   'logout_url':logout_url,
			   'login_user':login_user,
			   'is_user_admin':is_user_admin
			   }
	context.update(extra_context)
	return render_to_response('blog/index.html', context)

def index(request, p_id):
	if request.method == 'GET':
		tags = Tag.all()
		links = Link.all()
		if p_id == None:
			p_id = 1

		context = {'mod':'blog',
				   'tags':tags,
				   'comment_list':template.gen_comment_list_html(),
				   'links':links,
				   'category_list':template.gen_category_list_html(),
				   'link_list':template.gen_link_list_html(),
				   'diary_list':template.gen_diary_list_html(p_id),
				   'tag_list':template.gen_tag_list_html(),
				   }
		return gen_general_page(request, context)

##############
#Diary
##############
def list_diary(request, p_id):
	return HttpResponse(template.gen_diary_list_html(p_id))
	
def show_diary(request, diary_id):
	if request.is_ajax():
		return HttpResponse(template.gen_diary_html(diary_id))
	else:
		#如果不是Ajax请求，则生成整个页面
		tags = Tag.all()
		links = Link.all()

		context = {'mod':'blog',
				   'tags':tags,
				   'comment_list':template.gen_comment_list_html(),
				   'links':links,
				   'category_list':template.gen_category_list_html(),
				   'link_list':template.gen_link_list_html(),
				   'diary_list':template.gen_diary_html(diary_id),
				   'tag_list':template.gen_tag_list_html(),
				   }
		return gen_general_page(request, context)

def save_diary(request, diary_id=None):
	if request.method == 'POST':
		if diary_id:
			diary = db.get(diary_id)
		else:
			diary = Diary()
		#获取category
		diary_category = db.get(request.POST['diary_category'])
		
		#保存diary
		diary.title = request.POST['diary_title']
		diary.content = db.Text(request.POST['diary_content'])
		diary.category = diary_category.key()
		diary.put()
		
		#保存tag
		diary_tags = request.POST['diary_tags'].strip().split(' ')
		for diary_tag in diary_tags:
			tag = Tag.gql("where name='%s'" % diary_tag).get()
			if tag == None:
				tag = Tag(name=diary_tag)
			tag.diaries.append(diary.key())
			tag.put()
			
		#TODO:增加对Tag的修改
		return HttpResponse('ok')
	else:
		if diary_id:
			diary = db.get(diary_id)
		else:
			diary = None
	
	categories = Category.all()
	return render_to_response('blog/diary_form.html', {'diary': diary, 'categories':categories, })

def delete_diary(request, diary_id):
	if request.method == 'POST' and users.is_current_user_admin():
		id = diary_id[0:-1]
		db.delete(id)
		#TODO:删除后直接跳传到那一页
		return HttpResponse(template.gen_diary_list_html(1))
	else:
		return HttpResponse('access_deny')

##############
#Category
##############
def list_category(request):
	return HttpResponse(template.gen_category_list_html())

def delete_category(request, category_id):
	if request.method == 'POST' and users.is_current_user_admin():
		id = category_id[0:-1]
		db.delete(id)
		return HttpResponse(template.gen_category_list_html())
	else:
		return HttpResponse('access_deny')

def save_category(request, category_id):
	if request.method == 'POST':
		if users.is_current_user_admin():
			category = Category(name=request.POST['name'], order=0)
			category.put()
			return HttpResponse('ok')
		else:
			return HttpResponse('access_deny')
	else:
		if category_id:
			category = db.get(category_id)
		else:
			category = None
		
	return render_to_response('blog/category_form.html', {'category': category, })

def show_category_diary_list(request, category_id, page_id):
	if request.is_ajax():
		return HttpResponse(template.gen_diary_list_html(c_id=category_id, p_id=page_id))
	else:
		tags = Tag.all()
		links = Link.all()

		context = {'mod':'blog',
				   'tags':tags,
				   'comment_list':template.gen_comment_list_html(),
				   'links':links,
				   'category_list':template.gen_category_list_html(),
				   'link_list':template.gen_link_list_html(),
				   'diary_list':template.gen_diary_list_html(p_id=page_id, c_id=category_id),
				   'tag_list':template.gen_tag_list_html(),
				   }
		return gen_general_page(request, context)

##############
#Link
##############
def list_link(request):
	return HttpResponse(template.gen_link_list_html())

def save_link(request, link_id):
	if request.method == 'POST':
		if users.is_current_user_admin():
			link = Link(title=request.POST['title'], url=request.POST['url'], order=0)
			link.put()
			return HttpResponse('ok')
		else:
			return HttpResponse('access_deny')
	else:
		if link_id:
			link = db.get(link_id)
		else:
			link = None
		
	return render_to_response('blog/link_form.html', {'link': link, })

def delete_link(request, link_id):
	if request.method == 'POST' and users.is_current_user_admin():
		id = link_id[0:-1]
		db.delete(id)
		return HttpResponse(template.gen_link_list_html())
	else:
		return HttpResponse('access_deny')

##############
#Comment
##############
def save_comment(request, diary_id):
	if diary_id:
		parent_diary = db.get(diary_id)
		if parent_diary:
			if request.method == 'POST':
				comment = Comment(content=request.POST['content'], 
								  nick_name=request.POST['nick_name'], 
								  email=request.POST['email'], 
								  diary=parent_diary.key())
				comment.put()
				return HttpResponse(template.gen_diary_html(diary_id))
			if request.method == 'GET':
				return HttpResponse(template.gen_comment_form(diary_id))
	else:
		return HttpResponse('access_deny')
	
##############
#Tag
##############	
def show_tag_diary_list(request, tag_id, page_id):
	if request.is_ajax():
		return HttpResponse(template.gen_diary_list_html(t_id=tag_id, p_id=page_id))
	else:
		tags = Tag.all()
		links = Link.all()

		context = {'mod':'blog',
				   'tags':tags,
				   'comment_list':template.gen_comment_list_html(),
				   'links':links,
				   'category_list':template.gen_category_list_html(),
				   'link_list':template.gen_link_list_html(),
				   'diary_list':template.gen_diary_list_html(p_id = page_id, t_id = tag_id),
				   'tag_list':template.gen_tag_list_html(),
				   }
		return gen_general_page(request, context)